package jkim.plugin.daframe.ext.sql.views.actions;

import jkim.plugin.daframe.ext.sql.DaframeSQLLogger;
import jkim.plugin.daframe.ext.sql.model.DaframeSQLLoggerSetupInfo;

import org.eclipse.core.internal.resources.Folder;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

public class DaframeSQLLoggerMouseListener implements MouseListener {

	private Action copyLogAction;
	public DaframeSQLLoggerMouseListener(Action logInfoAction) {
		super();
		this.copyLogAction = logInfoAction;
	}
	public void mouseDoubleClick(MouseEvent e) {
		Table table = (Table) e.widget;
		String targetFileName = null;
		if (table != null) {
			TableItem ti = table.getItem(table.getSelectionIndex());
			if (ti != null) {
				targetFileName = ti.getText(2) + ".tsql";
			}
		}
		if (targetFileName != null) {
			DaframeSQLLoggerSetupInfo setupInfo = DaframeSQLLogger.getCurrentSetupInfo();
			Folder tsqlFolder = setupInfo.getTSQLFolder();
			IResource tsqlTarget = null;
			if (tsqlFolder != null) {
				tsqlTarget = tsqlFolder.findMember(targetFileName);
			}
			if (tsqlTarget == null) {
				// Copy action
				this.copyLogAction.run();
			} else {
				IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				try {
					IDE.openEditor(page, (IFile) tsqlTarget);
				} catch (PartInitException pie) {
				}
			}
		}
	}

	public void mouseDown(MouseEvent e) {
		// do nothing.
	}

	public void mouseUp(MouseEvent e) {
		// do nothing.
	}
}
